
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <esp_log.h>
#include <nvs_flash.h>
#include <sys/param.h>
#include "esp_tls_crypto.h"
#include <esp_http_server.h>
#include "esp_event.h"
#include "esp_netif.h"
#include "esp_tls.h"



/***************************** */ /*
    依赖函数
*/ /****************************** */
extern esp_err_t write_nvs_str(const char* namespace,const char* key,const char* value);

extern int configSetOk();
#include "nvs_data_define.h"





/* A simple example that demonstrates how to create GET and POST
 * handlers for the web server.
 */

static const char *TAG = "usi handler";

static esp_err_t echo_post_handler(httpd_req_t *req)
{
    char buf[256];
    char wifi_name[32];
    char wifi_password[32];
    //
    char server_ipv4[32];
    char server_port[32];
    //
    int ret, remaining = req->content_len;
 
    while (remaining > 0) {
        memset(buf, 0, 100);
        memset(wifi_name, 0, 32);
        memset(wifi_password, 0, 32);

        /* Read the data for the request */
        if ((ret = httpd_req_recv(req, buf,
                        MIN(remaining, sizeof(buf)))) <= 0) {
            if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
                /* Retry receiving if timeout occurred */
                continue;
            }
            return ESP_FAIL;
        }
 
        /* Send back the same data */
        httpd_resp_send_chunk(req, buf, ret);
        remaining -= ret;

        /*********** wifi热点*/
        {
        esp_err_t e = httpd_query_key_value(buf,"ssid",wifi_name,sizeof(wifi_name));
        if(e == ESP_OK) {
            printf("ssid = %s\r\n",wifi_name);
            write_nvs_str(NVS_NAMESPACE_config, NVS_KEY_ssid, wifi_name);
        }
        else {
            printf("error = %d\r\n",e);
        }
        }

        /*********** */
        {
        esp_err_t e = httpd_query_key_value(buf,"password",wifi_password,sizeof(wifi_password));
        if(e == ESP_OK) {
            printf("pswd = %s\r\n",wifi_password);
            write_nvs_str(NVS_NAMESPACE_config, NVS_KEY_psw, wifi_password);
        }
        else {
            printf("error = %d\r\n",e);
        }
        }

        /*********** 服务器*/
        {
        esp_err_t e = httpd_query_key_value(buf,"ipv4", server_ipv4, sizeof(server_ipv4));
        if(e == ESP_OK) {
            printf("ipv4 = %s\n", server_ipv4);
            write_nvs_str(NVS_NAMESPACE_config, NVS_KEY_ipv4, server_ipv4);
        }
        else {
            printf("error = %d\r\n",e);
        }
        }

        /*********** */
        {
        esp_err_t e = httpd_query_key_value(buf, "port", server_port, sizeof(server_port));
        if(e == ESP_OK) {
            printf("port = %s\n", server_port);
            write_nvs_str(NVS_NAMESPACE_config, NVS_KEY_port, server_port);
        }
        else {
            printf("error = %d\r\n",e);
        }
        }


        /* Log data received */
        ESP_LOGI(TAG, "=========== RECEIVED DATA ==========");
        ESP_LOGI(TAG, "%.*s", ret, buf);
        ESP_LOGI(TAG, "====================================");
    }

    configSetOk();

    // End response
    httpd_resp_send_chunk(req, NULL, 0);
    if(strcmp(wifi_name ,"\0")!=0 && strcmp(wifi_password,"\0")!=0)
    {
        ESP_LOGI(TAG, "set wifi name and password successfully! goto station mode");
    }
    return ESP_OK;
}


httpd_uri_t echo = {
    .uri       = "/wifi_data",
    .method    = HTTP_POST,
    .handler   = echo_post_handler,
    .user_ctx  = NULL
};


static esp_err_t html_default_get_handler(httpd_req_t *req)
{
    // /* Send HTML file header */
    // httpd_resp_sendstr_chunk(req, "<!DOCTYPE html><html><body>");
 
    /* Get handle to embedded file upload script */
    extern const unsigned char upload_script_start[] asm("_binary_upload_script_html_start");
    extern const unsigned char upload_script_end[] asm("_binary_upload_script_html_end");
    const size_t upload_script_size = (upload_script_end - upload_script_start);
 
    /* Add file upload form and script which on execution sends a POST request to /upload */
    httpd_resp_send_chunk(req, (const char *)upload_script_start, upload_script_size);
 
    /* Send remaining chunk of HTML file to complete it */
    httpd_resp_sendstr_chunk(req, "</body></html>");
 
    /* Send empty chunk to signal HTTP response completion */
    httpd_resp_sendstr_chunk(req, NULL);
    return ESP_OK;
}
 
httpd_uri_t html_default = {
    .uri = "/", // Match all URIs of type /path/to/file
    .method = HTTP_GET,
    .handler = html_default_get_handler,
    .user_ctx = "html" // Pass server data as context
};

